import React, { PureComponent } from 'react';
import axios from 'axios';
import { web3, walletListContract, getWalletContract } from '../../config';
import { withRouter } from 'react-router-dom';
import { Button, Message, Tag } from '@alifd/next';
import IceTitle from '@icedesign/title';
import IceContainer from '@icedesign/container';

const { Group: TagGroup } = Tag;

class Partner extends PureComponent {
  static displayName = 'Partner';
  static propTypes = {};
  static defaultProps = {};

  constructor(props){
    super(props);
    this.state = {
      workData: [],
      workId: "",
      role: "",
      userId: "",
      userWalletAddress: "",
      authorWalletAddress: "",
      authorId: "",
      price: "",
      workImages: "",
      workType: ""
    };
    this.getDetail(this.props.match.params.workId);
  }

  getDetail = (_workId) => {
    const userId = localStorage.getItem("id");
    // console.log('userId', userId);
    axios.get('http://localhost:9080/work/' + _workId.slice(7)).then((res) => {
        // console.log(res.data);
        // 需要通过workId传回来的数据判断一下此用户的身份
        let role;
        if(userId.toString() === res.data.authorId.toString()) {
          // 当前用户是此作品的作者
          role = 1;
        }else if(userId.toString() === "" || userId == null){
          // 当前用户是游客/未登录状态
          role = 0;
        }else {
          // 当前用户已登陆但不是作者
          role = 2;
        }
        // console.log('res.data.authorId', res.data.authorId);
        console.log('role, ', role);
        this.setState({
          workData: res.data,
          workId: _workId,
          role: role,
          userId: userId,
          authorId: res.data.authorId,
          price: res.data.authPrice,
          workImages: res.data.workImages,
          workType: res.data.workType
        });
    }).catch((res)=>{
        console.log(res);
    });
  }

  getUserWalletAddress = async (_id) => {
    await axios.get('http://localhost:9080/users/'+_id, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      console.log('walletAddress', res.data.walletAddress);
      this.setState({
        workData: res.data,
        userWalletAddress: res.data.walletAddress
      });
    }).catch(() => {
      console.log('error');
      return 0;
    });
  }

  getAuthorWalletAddress = async (_id) => {
    console.log(_id);
    await axios.get('http://localhost:9080/users/'+_id, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      this.setState({
        workData: res.data,
        authorWalletAddress: res.data.walletAddress
      });
    }).catch(() => {
      console.log('error');
      return 0;
    });
  }

  buyWork = async (_role, _workAddress, _authPrice) => {
    let _authorId = this.state.authorId;
    console.log(_authorId);
    // 根据role判断当前用户
    // role = 0 未登录用户 弹框提醒登录
    // role = 1 当前用户是此作品作者 弹框提醒是作者
    // role = 2 当前用户可购买 首先根据userId, _authorId找到用户钱包地址
    //  没有钱包 弹框提醒创建钱包
    //  有钱包
    //    钱包余额不够，提醒充值
    //    钱包余额够，正常购买
    //      首先生成订单
    //      其次购买者的钱包金额改变
    //      卖方钱包金额改变
    const [adminWallet] = await web3.eth.getAccounts();
    console.log('adminWallet', adminWallet);
    if(_role === 0) {
      alert("请登录！");
    }else if(_role === 1) {
      alert("您是作者！");
    }else if(_role === 2) {
      await this.getUserWalletAddress(this.state.userId);
      // console.log('userWalletAddress', this.state.userWalletAddress);
      const userWalletContract = await getWalletContract(this.state.userWalletAddress);
      const userWalletDetail = await userWalletContract.methods.getWalletDetail().call({
        from: adminWallet
      });
      let [_userId, _balance, _cost, _income] = Object.values(userWalletDetail);
      if(_balance >= _authPrice) {
        // 余额够，正常购买
        // 首先生成订单
        const ordertype = "授权订单";
        const createTime = new Date().toLocaleString();
        const orderMoney = _authPrice;
        const moneyType = "CR";
        const orderInfo = "授权购买";
        const buyerId = this.state.userId;
        const sellerId = '"'+this.state.authorId+'"';
        console.log(sellerId);
        const status = 1;
        await walletListContract.methods.createOrder(ordertype, createTime, orderMoney, 
          moneyType, orderInfo, buyerId, sellerId, status).send({
          from: adminWallet
        });
        const OrderAddress = await walletListContract.methods.getLatestOrderAddress().call();
        console.log(OrderAddress);
        // 其次购买者钱包金额改变
        const userBalance = _balance - _authPrice;
        const userCost = _cost + _authPrice;
        await userWalletContract.methods.setWalletDetail(userBalance, userCost, _income).send({
          from: adminWallet
        });
        // 最后卖方钱包金额改变
        // let authorWalletAddress = 
        await this.getAuthorWalletAddress(this.state.authorId);
        const authorWalletContract = await getWalletContract(this.state.authorWalletAddress);
        const authorWalletDetail = await authorWalletContract.methods.getWalletDetail().call({
          from: adminWallet
        });
        let [_authorId, _authorBalance, _authorCost, _authorIncome] = Object.values(authorWalletDetail);
        const authorBalance = _authorBalance + _authPrice;
        const authotIncome = _authorIncome + _authPrice;
        await authorWalletContract.methods.setWalletDetail(authorBalance, _authorCost, authotIncome).send({
          from: adminWallet
        });

        // 
        axios.post("http://localhost:9080/order/add", {
          type: ordertype,
          orderMoney: orderMoney,
          moneyType: moneyType,
          orderInfo: orderInfo,
          buyerId: this.state.userId,
          sellerId: this.state.authorId,
          status: status
        }).then((res) => {
          Message.success('提交成功');
        }).catch((err) => {
          console.log(err);
          Message.warning('提交失败，请联系管理员或稍后重试！');
        });

        axios.post("http://localhost:9080/copyright/auth/add", {
          userId: this.state.userId,
          workId: this.state.workId.slice(7),
          authType: 1,
          price: this.state.price
        }).then((res) => {
          Message.success('提交成功');
        }).catch((err) => {
          console.log(err);
          Message.warning('提交失败，请联系管理员或稍后重试！');
        });
        alert("已完成购买！");
      }else {
        alert("余额不够！请充值");
      }
    }else {
      return false;
    }
  }

  render() {
    const { workData, workImages, workType, authorId } = this.state;
    const workAddress = workData.certAddress;
    console.log('workAddress', workAddress);
    const authPrice = workData.authPrice;
    const images = workImages.split(",");
    const types = workType.split(",");
    // console.log(images);
    const role = this.state.role;
    console.log(authorId);
    return (
      <IceContainer style={{ margin: "50px auto", width: "800px"}}>
        <h1 style={{ textAlign: "center" }}>{workData.workName}</h1>
        <IceTitle text={workData.workName} />
        {
          images.map((item, index) => {
            return (
              <img
                key={index}
                src={item}
                style={{maxWidth: "200px", maxHeight: "400px", border: '1px solid #ccc', margin: '10px'}}
              />
            )
          })
        }
        <IceTitle text="作品描述" />
        <p>
          作者：{workData.authorName}（用户ID：{workData.authorId}）
        </p>
        <p style={styles.desc}>
          {workData.workDesc}
        </p>
        <p>
          购买价格：{workData.authPrice}
        </p>
        <p>
          作品ID：{workData.workId}
        </p>
        <p>
          作品链上地址：{workData.certAddress}
        </p>
        <TagGroup>
          {
            types.map((item, index) => {
              return (
                <Tag type="primary" size="medium" key={index}>
                  {item}
                </Tag>
              )
            })
          }
        </TagGroup>
        <Button
          style={styles.extraButton}
          onClick={() => this.buyWork(role, workAddress, authPrice)}
        >
          购买 &gt;
        </Button>
      </IceContainer>
    );
  }

  // componentDidMount() {
  //   // console.log(this.props.match.params.workId);
  //   this.getDetail(this.props.match.params.workId);
  // }
}

const styles = {
  wrapper: {
    position: 'relative',
    overflow: 'hidden',
    height: 690,
  },
  productContent: {
    position: 'relative',
    zIndex: 1,
    display: 'flex',
    justifyContent: 'center',
    marginTop: 120,
  },
  titleLine: {
    width: 140,
    height: 2,
    marginTop: 17,
    background: '#FFFFFF',
    borderLeft: '2px solid ##5fb2f8',
  },
  titleHighlightLine: {
    background: '#3080FE',
    height: 2,
    width: 33,
  },
  productSnapshot: {},
  productInfo: {
    width: 400,
    marginRight: 90,
    marginTop: 40,
  },
  title: {
    color: '#223C4E',
    fontSize: 36,
  },
  desc: {
    color: '#6D7A82',
    fontSize: 16,
    lineHeight: 1.5,
    marginTop: 24,
  },
  extraButton: {
    marginTop: 35,
    borderColor: '#3080FE',
    background: 'transparent',
    color: '#3080FE',
  },
  clipBackground: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
    background: '#FAFAFA',
    clipPath: 'polygon(0 15%, 100% 0, 100% 85%, 0% 100%)',
  },
};

export default withRouter(Partner);